<?php
/**
 * DB_Shard_Guang
 *
 * 作者: 王景辉(khairiwang@tencent.com)
 * 创建时间: 2013-10-21 21:30:12
 * 修改记录:
 *
 * $Id$
 */
class DB_Shard_Guang extends DB_Shard {

    // 数据库分表模值
    const DB_MASK = 0x3FF;

    /**
     * 此分库规则下的数据库配置信息
     *
     */
    private $_db = array();

    /**
     * 分库的关键字
     * @var array
     */
    public $_shardKey;

    /**
     * @var array
     */
    private $_options;

    public $table;

    public function __construct($options, $shardKey = array()) {

        $this->_options = $options;
        $this->_shardKey = $shardKey;
        $this->shard($options['config'], $shardKey);
    }

    /**
     * shard
     * 分片处理
     *
     * @param  array $shards
     * @param  array $shardKey
     * @return boolean
     */
    protected function shard($shards, $shardKey = array()) {

        try {

            $dbSuffix = $this->_getDbSuffix($shardKey);
            $this->_db['dsn'] = sprintf($shards['dsn'], $dbSuffix);
            $this->_db['user'] = $shards['user'];
            $this->_db['password'] = $shards['password'];
            $this->_db['charset'] = $shards['charset'];
            $this->_db['persistent'] = $shards['persistent'];

        } catch (Exception $e) {
            throw new Yaf_Exception($e);
        }

        return true;
    }

    /**
     * _getDbSuffix
     * 获取数据库后缀
     */
    public static function _getDbSuffix($shardKey) {

        // 图片表:搭配
        if (array_key_exists('data_id', $shardKey)) {
            $hash = $shardKey['data_id'];

            // 用户优惠券
        } elseif (array_key_exists('uin', $shardKey)) {
            $hash = $shardKey['uin'];

            // 指定库名
        } elseif (array_key_exists('hash', $shardKey)) {
            return $shardKey['hash'];

            // 商品相关
        } else {
            $hash = 5381;
            $hashStr = $shardKey['provider_id'] . '&' . $shardKey['goods_id'];
            $hashStrLen = strlen($hashStr);
            for ($i = 0; $i < $hashStrLen; $i++) {
                $hash += ($hash << 5) + ord($hashStr[$i]);
                while ($hash >= 4294967296) {
                    $hash -= 4294967296;
                }
            }
            $hash = $hash & 0x7FFFFFFF;
        }

        return $hash & self::DB_MASK;
    }

    /**
     * getDB
     * 获取数据库配置
     *
     * @return array
     */
    public function getDB() {

        return  $this->_db;
    }
}
